<template>
  <div class="layout-main-conent">
    <a-card :bordered="false" style="margin-bottom: 15px" :bodyStyle="{ paddingBottom: '0' }">
      <a-form :labelCol="{ span: 6, offset: 0 }" :wrapper-col="{ span: 18 }">
        <a-row :gutter="16">
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <a-form-item label="日期筛选">
              <a-range-picker v-model:value="searchModelRef.date" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <a-form-item label="搜索">
              <a-input placeholder="请输入公告标题/发布人" v-model:value="searchModelRef.title" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
            <div class="text-align-right" style="padding-bottom: 24px">
              <a-button type="primary" @click="searchFormSubmit">搜索</a-button>
              <a-button @click="searchResetFields" style="margin-left: 8px;">重置</a-button>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" class="table-card">
      <template #extra>
        <div style="width: 100%;display: flex">
          <a-button type="primary" @click="publishAnnouncement">发布公告</a-button>
          <span style="flex:1"><a-button style="margin-left: 8px" @click="deleteDatas">删除</a-button></span>
          <a-button type="primary" @click="() => setCreateFormVisible(true)">新建</a-button>
        </div>
      </template>
      <a-table row-key="id" :columns="columns" :data-source="list" :loading="loading" :pagination="pagination"
        :row-selection="rowSelection">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'isConfirm'">
              <span v-if="record.type === '闭环公告'">{{ `${record.confirmNum || 0}` + '/' + record.unconfirmedNum || 0
              }}</span>
            <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'action'">
            <!-- 已发布 -->
            <template v-if="record.announceStatus === '1'">
              <a-button type="link" @click="() => onPreview(record)">查看</a-button>
              <a-button type="link" @click="() => withdrawAnnouncement(record)">撤回</a-button>
            </template>
            <!-- 未发布 -->
            <template v-else>
              <a-button type="link" @click="() => detailUpdateData(record)">编辑</a-button>
              <a-button type="link" @click="() => deleteTableData(record)" class="delete-button">删除</a-button>
            </template>
            </template>
          </template>
      </a-table>
    </a-card>
    <create-form :visible="createFormVisible" :onCancel="() => setCreateFormVisible(false)"
      :onSubmitLoading="createSubmitLoading" :onSubmit="createSubmit" />

    <update-form v-if="updateFormVisible" :visible="updateFormVisible" :values="updateRoleData"
      :operationType="formOperationType" :onCancel="() => updataFormCancel()" :onSubmitLoading="updateSubmitLoading"
      :onSubmit="updateSubmit" />
    <delete-modal :visible="deleteVisible" :onCancel="() => (deleteVisible = false)" :onSubmit="deleteSubmit" />
  </div>
</template>
<script lang="ts">
export default {
  name: "AnnouncementManager",
};
</script>
<script lang="ts" setup>
import { onMounted, ref, reactive } from "vue";
import { message, Modal } from "ant-design-vue";
// demandPresentation
import CreateForm from "./components/CreateForm.vue";
import UpdateForm from "./components/UpdateForm.vue";
import { TableListItem, SelectedRecord, OperationType } from "./data";
import {
  queryList,
  detailData,
  createData,
  updateData,
  removeData,
  publishData,
  withdraw
} from "./service";
import DeleteModal from "@/views/component/DeleteModal.vue";
import { columns } from './config'
import dayjs, { Dayjs } from 'dayjs';
const deleteVisible = ref(false);
const selectedRecords = ref<(string | number)[]>([]);
// 列表分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0, // 假设总共有100条数据
  showTotal: (total) => `共 ${total} 条数据`,
  onChange: (page, pageSize) => {
    // 分页改变时的回调函数
    pagination.current = page;
    pagination.pageSize = pageSize;
    getList();
  },
  showSizeChanger: true,
  showQuickJumper: true,
});
const rowSelection = ref({
  checkStrictly: false,
  preserveSelectedRowKeys: false,
  onChange: (selectedRowKeys: (string | number)[], selectedRows: any) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows, selectedRows.value);
    selectedRecords.value = selectedRows.map(item => item.id)
  }
});
const list = ref([]);
const loading = ref<boolean>(false);
// 表单值
const searchModelRef = ref({
  date: [],
  title: "",
});
// 新增弹框 - visible
const createFormVisible = ref<boolean>(false);
// 新增弹框 - 提交 loading
const createSubmitLoading = ref<boolean>(false);
// 编辑弹框 data
const updateRoleData = ref({});
// 编辑弹框 - visible
const updateFormVisible = ref<boolean>(false);
// 编辑弹框 - 提交 loading
const updateSubmitLoading = ref<boolean>(false);
const formOperationType = ref<OperationType>('create')
onMounted(() => {
  getList();
});
const deleteSubmit = async () => {
  const res = await removeData({ ids: selectedRecords.value });
  if (res.success) {
    selectedRecords.value = [];
    getList();
    message.success("删除成功");
  }
  deleteVisible.value = false;
};
// 获取数据
const getList = async (): Promise<void> => {
  loading.value = true;
  const { date, title } = searchModelRef.value
  const beginTime = date.length ? dayjs(date[0]).format('YYYY-MM-DD') + ' 00:00' : ''
  const endTime = date.length ? dayjs(date[1]).format('YYYY-MM-DD') + ' 59:59' : ''
  const params = {
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
    title, beginTime, endTime
  };
  const res = await queryList(params);
  if (res.success) {
    list.value = res.data.records;
    list.value.forEach((ele: any, index) => {
      ele.enableStatus = ele.enableStatus === "1";
      ele.index = (pagination.current - 1) * pagination.pageSize + index + 1
    });
    pagination.total = res.data.total;
  }
  loading.value = false;
};

// 搜索
const searchFormSubmit = async () => {
  getList();
};
const searchResetFields = async () => {
  searchModelRef.value = {
    date: [],
    title: "",
  };
  searchFormSubmit();
};

const setCreateFormVisible = (val: boolean) => {
  createFormVisible.value = val;
};

// 新增弹框 - 提交
const createSubmit = async (values: Omit<TableListItem, "id">) => {
  createSubmitLoading.value = true;
  const { publishDate, publishTime, ifTimedRelease } = values
  const timedReleaseTime = ifTimedRelease ? (publishDate ? dayjs(publishDate).format('YYYY-MM-DD') : '') + ' ' + (publishTime ? dayjs(publishTime).format('HH:mm') : '') : ""
  const params = {
    announcePerson: values.announcePerson || [],
    announceScope: values.announceScope || [],
    content: values.content || '',
    fileIds: values.fileIds || [],
    ifTimedRelease: ifTimedRelease || false,
    timedReleaseTime: timedReleaseTime.trim() || '',
    title: values.title || '',
    type: values.type || '',
    announceStatus: values.announceStatus || '',
  }

  try {
    const res = await createData(params);
    if (res.success) {
      setCreateFormVisible(false);
      message.success("新增成功！");
      getList();
    }
  } finally {
    createSubmitLoading.value = false;
  }
};

const onPreview = async (record: any) => {
  const params = {
    id: record.id,
  };
  const res = await detailData(params);

  if (res.success) {
    updateRoleData.value = { ...res.data, type: res.data.code };
    setUpdateFormVisible(true);
    formOperationType.value = 'view'
  }
}
const detailUpdateData = async (record: any) => {

  const params = {
    id: record.id,
  };
  const res = await detailData(params);

  if (res.success) {
    updateRoleData.value = { ...res.data, type: res.data.code };
    setUpdateFormVisible(true);
    formOperationType.value = 'edit'
  }
};

const setUpdateFormVisible = (val: boolean) => {
  updateFormVisible.value = val;
};
const updataFormCancel = () => {
  setUpdateFormVisible(false);
};

// 编辑弹框 - 提交
const updateSubmit = async (values: TableListItem) => {
  const { publishDate, publishTime, ifTimedRelease } = values
  const timedReleaseTime = ifTimedRelease ? dayjs(publishDate).format('YYYY-MM-DD') + ' ' + dayjs(publishTime).format('HH:mm') : ""
  const params = {
    announcePerson: values.announcePerson || [],
    announceScope: values.announceScope || [],
    content: values.content || '',
    fileIds: values.fileIds || [],
    ifTimedRelease: ifTimedRelease || false,
    timedReleaseTime: timedReleaseTime || '',
    title: values.title || '',
    type: values.type || '',
    id: values.id,
    announceStatus: values.announceStatus || '',
  }

  try {
    updateSubmitLoading.value = true;
    const res = await updateData(params);
    if (res.success) {
      updataFormCancel();
      message.success("编辑成功！");
      getList();
    }
  } finally {
    updateSubmitLoading.value = false;
  }
};
// 撤回
const withdrawAnnouncement = async (record) => {
  // Modal.confirm({
  //   title: '撤回',
  //   content: '确定撤回吗？',
  //   okText: '确认',
  //   cancelText: '取消',
  //   maskClosable: true,
  //   onOk: async () => {
  const res = await withdraw({ id: record.id })
  if (res.success) {
    message.success('撤回成功！');
    getList();
  }
  // }
  // });

}
// 批量删除
const deleteDatas = async () => {
  if (!selectedRecords.value.length) {
    message.warning("请选择要删除的数据！")
    return
  }
  deleteVisible.value = true;
}
// 删除
const deleteTableData = async (record) => {
  deleteVisible.value = true;
  selectedRecords.value = [record.id];
};
// 发布公告
const publishAnnouncement = async () => {
  if (selectedRecords.value.length) {
    const res = await publishData({ ids: selectedRecords.value })
    if (res.success) {
      getList();
    }
    console.log('selectedRecords.value', selectedRecords.value);

  } else {
    message.warning("请选择要发布的数据！")
  }

}
</script>
<style scoped lang="less">
.delete-button {
  color: red;
}

.role-manager {
  margin-right: 20px;
}

.table-card {
  :deep(.ant-card-body) {
    padding: 0px 24px 24px 24px;
  }
}

:deep(.ant-card-head) {
  border: none;
}

:deep(.ant-card-extra) {
  width: 100%;
  margin-left: 0;
}
</style>
